package com.onlinevideo.servlet;


import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.Page;
import com.onlinevideo.entity.Role;
import com.onlinevideo.entity.User;
import com.onlinevideo.service.RoleService;
import com.onlinevideo.service.impl.RoleServiceImpl;
import com.onlinevideo.service.impl.UserServiceImpl;
import com.onlinevideo.util.MyBeanUtils;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 目前有登录和注册两个功能
 * 暂时不支持验证码（防止表单重复提交），有待完善
 */
public class UserServlet extends BaseServlet {
    private UserServiceImpl userService = new UserServiceImpl();
    private PrintWriter writer = null;
    HttpSession session = null ;

    private RoleService roleService = new RoleServiceImpl();

    /**
     * 登录 action="login"
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException getWriter()异常上抛
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException, ServletException {

        writer = resp.getWriter();
        session = req.getSession();
        //判断用户名和密码
        User user = userService.queryByUsernameAndPassword(MyBeanUtils.set(User.class, req.getParameterMap()));
        String url = "";
        if (user != null) {
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(15 * 60 );
            if(user.getUserStatus()==0){
                url = "../gateway?action=userinfocomplete";
                writer.write(JSONUtil.toJsonStr(ResultBean.scLoginSuccess("登陆成功,但是请完善个人信息",url)));
                return;
            }
            //根据用户中的角色id查找用户的角色信息
            Role role = roleService.queryById(user.getRoleId());
            //如果角色的状态为0则为管理员，否则为前台用户
            if(role.getRoleStatus()==0){
                session.setAttribute("bguser",user);
                url = "../gateway?action=bgindex";
            }else {
                url = "../gateway?action=mine";
            }
            writer.write(JSONUtil.toJsonStr(ResultBean.scLoginSuccess("用户" + user.getNickname() +"登陆成功",url)));
        } else {
            url="#";
            writer.write(JSONUtil.toJsonStr(ResultBean.scLoginError("账号密码不一致或用户不存在",url)));
        }
    }

    /**
     * 注册 action="register"
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException getWriter()异常上抛
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        session = req.getSession();
        String username = req.getParameter("username");
        String emailVcode = String.valueOf(session.getAttribute("emailVcode"));
        String vcode = req.getParameter("vcode");
        if(emailVcode==null){
            writer.write(JSONUtil.toJsonStr(ResultBean.scRegisterError("验证码已经失效，请重新获取")));
            return;
        }
        if(!emailVcode.equals(vcode)){
            writer.write(JSONUtil.toJsonStr(ResultBean.scRegisterError("验证码错误，请重新获取")));
            return;
        }
        //判断用户名是否存在
        Long userCount = userService.queryByUsername(username);
        if (userCount > 0L) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scRegisterError(username + "用户名已存在")));
            return;
        }
        String password = req.getParameter("password");
        //将用户信息添加到数据库并判断是否添加成功
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int insert = userService.insert(user);
        if (insert > 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scRegisterSuccess(username+"注册成功,请移步到登录界面进行登录系统!")));
            return;
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scRegisterError(username + "注册失败")));
        }

    }

    protected void loginOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        session = req.getSession();
        session.setMaxInactiveInterval(0);
        session.invalidate();
        resp.sendRedirect("../gateway?action=login");
    }
    protected void userInfoComplete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writer = resp.getWriter();
        session = req.getSession();
        User user = (User)session.getAttribute("user");
        String url = "";
        if (user != null) {
            User user1 = MyBeanUtils.set(User.class, req.getParameterMap());
            if(user1.getNickname().trim().length()<=0){
                url="#";
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("未输入昵称",url)));
                return;
            }
            if(user1.getPhone().trim().length()<=0){
                url="#";
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("未输入手机号",url)));
                return;
            }
            if(user1.getEmail().trim().length()<=0){
                url="#";
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("未输入邮箱",url)));
                return;
            }
            user.setNickname(user1.getNickname());
            user.setPhone(user1.getPhone());
            user.setEmail(user1.getEmail());
            user.setUserStatus(1);
            int result = userService.update(user);
            if(result>0){
                url = "../gateway?action=mine";
                writer.write(JSONUtil.toJsonStr(ResultBean.scLoginSuccess("用户" + user.getNickname() +"信息完善成功",url)));
            }else {
                url = "#";
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("用户" + user.getUsername() +"信息完善失败",url)));
            }
        } else {
            url="#";
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("用户未登录，无法完善用户信息，请重新登录",url)));
        }
    }

    /**
     * 新增会员信息  action="insert"
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException getWriter()异常上抛
     */
    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InstantiationException {
       /* //用户名 name="username"
        String username = req.getParameter("username");
        writer = resp.getWriter();
        //判断用户名是否存在
        Long userCount = userService.queryByUsername(username);
        if (userCount > 0L) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scRegisterError(username + "用户名已存在")));
            return;
        }
        //将用户信息添加到数据库并判断是否添加成功
        //User user =  BeanUtils.set(User.class,req.getParameterMap());
        //int insert = userService.insert(user);

        //TODO:传数据给前端，返回成功或失败*/
    }

    /**
     * 修改会员信息 action="update"
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException getWriter()异常上抛
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        User user = (User) req.getSession().getAttribute("user");
        Map parameterMap = req.getParameterMap();
        MyBeanUtils.fillReq(User.class, parameterMap,user);
        System.out.println(user);
        int update = userService.update(user);
        if (update>0){
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("修改成功")));
        }else {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationError("修改失败")));
        }
    }

    /**
     * 删除 action="delete"
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException getWriter()异常上抛
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        writer =resp.getWriter();
        User user = MyBeanUtils.set(User.class, req.getParameterMap());
        int result = userService.delete(user.getId());
        if(result>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("编号:"+user.getId()+"删除成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("编号:"+user.getId()+"删除失败")));
        }
    }
    //后台用户管理查询全部
    protected void queryAll(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<User> users = userService.queryAll();
        req.setAttribute("users", users);
        req.setAttribute("username", "username");
        req.getRequestDispatcher("../gateway?action=userlist").forward(req, resp);
    }

    protected void queryByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String pageNoStr = req.getParameter("pageNo");
        if (pageNoStr == null) {
            pageNoStr = "1";
        }
        Integer pageNo = Integer.valueOf(pageNoStr);
        Page<User> users = userService.queryByPage(null,pageNo);
        req.getSession().setAttribute("users", users);
        resp.sendRedirect(req.getContextPath()+"../gateway?action=userlist");
    }
    //后台用户管理条件查询
    protected void queryByCondition(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        User user = MyBeanUtils.set(User.class, req.getParameterMap());
        String username = user.getUsername();
        String phone = user.getPhone();
        List<User> users = userService.queryLike(user.getUsername(), user.getPhone());
        HttpSession session = req.getSession();
        session.setAttribute("users",users);
        session.setAttribute("bg_username",username);
        session.setAttribute("bg_phone",phone);
        resp.sendRedirect(req.getContextPath()+"../gateway?action=userlist");
    }
    //个人主页回填用户信息
    protected void getUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationError("用户未登录，请登录", "../view/logo.jsp")));
        }else {
            resp.getWriter().write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("信息回填成功",user)));
        }
    }
    //上传头像
    protected void uploadLogo(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        session = req.getSession();
        writer = resp.getWriter();
        User user = (User) session.getAttribute("user");
        List<FileItem> fileDomain = (List<FileItem>) req.getAttribute("fileDomain");
        String url = userService.uploadLogo(fileDomain);
        user.setLogoUrl(url);
        int update = userService.update(user);
        if (update>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("上传成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("上传失败")));
        }
    }
    //后台添加用户
    protected void addUser(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        writer = resp.getWriter();
        String username = (String) req.getAttribute("username");
        String password = (String) req.getAttribute("password");
        String userType = (String) req.getAttribute("userType");
        String userStatus = (String) req.getAttribute("userStatus");
        String userValidity = (String) req.getAttribute("userValidity");
        String addPhone = (String) req.getAttribute("addPhone");
        String addNickname = (String) req.getAttribute("addNickname");
        String addEmail = (String) req.getAttribute("addEmail");
        List<FileItem> fileDomain = (List<FileItem>) req.getAttribute("fileDomain");
        String url = userService.uploadLogo(fileDomain);
        User user = new User(null,username,password,addPhone,addNickname,Long.valueOf(userType),addEmail,Integer.valueOf(userStatus),Integer.valueOf(userValidity),url,String.valueOf(System.currentTimeMillis()));
        int insert = userService.insertBg(user);
        if (insert>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("添加成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("添加失败")));
        }
    }
    //后台修改用户
    protected void editUser(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = (String) req.getAttribute("username");
        String password = (String) req.getAttribute("password");
        String userId = (String) req.getAttribute("userId");
        String userType = (String) req.getAttribute("userType");
        String userStatus = (String) req.getAttribute("userStatus");
        String userValidity = (String) req.getAttribute("userValidity");
        String editPhone = (String) req.getAttribute("editPhone");
        String editNickname = (String) req.getAttribute("editNickname");
        String editEmail = (String) req.getAttribute("editEmail");
        List<FileItem> fileDomain = (List<FileItem>) req.getAttribute("fileDomain");
        String url = userService.uploadLogo(fileDomain);
        Long id = Long.valueOf(userId);
        if (url == null) {
            url=userService.queryById(id).getLogoUrl();
        }
        writer = resp.getWriter();
        User user = new User(id,username,password,editPhone,editNickname,Long.valueOf(userType),editEmail,Integer.valueOf(userStatus),Integer.valueOf(userValidity),url,String.valueOf(System.currentTimeMillis()));
        int update = userService.update(user);
        if (update>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("修改成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("修改失败")));
        }
    }

}
